<template>
  <el-dialog
      v-model="dialogVisible"
      title="批量导出论文"
      width="80%"
      :before-close="handleClose"
  >
    <div class="export-content">
      <!-- 字段选择区域 -->
      <div class="field-selection">
        <p class="section-label">
          字段选择区域
          <el-icon><QuestionFilled /></el-icon>
        </p>
        <div class="field-tags">
          <el-tag
              v-for="field in fields"
              :key="field.key"
              class="field-tag"
              :effect="field.selected ? 'light' : 'plain'"
              @click="toggleField(field)"
          >
            {{ field.label }}
          </el-tag>
        </div>
      </div>

      <!-- 表格预览区域 -->
      <el-table
          :data="tableData"
          style="width: 100%"
          :border="true"
          class="export-table"
      >
        <el-table-column
            v-for="field in selectedFields"
            :key="field.key"
            :prop="field.key"
            :label="field.label"
            :min-width="field.width || 120"
        />
      </el-table>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleExport">下载Excel</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { QuestionFilled } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { exportPaper } from '@/api/result/papers.js' // 确保 API 正确引入

const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true
  },
  papers: {
    type: Array,
    required: true
  }
})

const emit = defineEmits(['update:modelValue'])

const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 导出字段配置（根据实际需求调整）
const fields = ref([
  { key: 'nickName', label: '用户昵称', selected: true },
  { key: 'title', label: '标题', selected: true, width: 200 },
  { key: 'paperType', label: '论文类型', selected: true },
  { key: 'journalName', label: '期刊名', selected: true, width: 180 },
  { key: 'indexing', label: '期刊收录', selected: true },
  { key: 'impactFactor', label: '影响因子', selected: true },
  { key: 'issn', label: '期刊ISSN', selected: true },
  { key: 'volumeNumber', label: '卷', selected: true },
  { key: 'issueNumber', label: '期', selected: true },
  { key: 'pageRange', label: '页码', selected: true },
  { key: 'publishDate', label: '发表年份', selected: true },
  { key: 'authorRank', label: '我的排名', selected: true },
  { key: 'doi', label: 'DOI', selected: true },
  { key: 'authorInfo', label: '作者列表', selected: true, width: 200 }
])

const selectedFields = computed(() => fields.value.filter(f => f.selected))

const tableData = ref([])

// 监听 props.papers 变化，构建 tableData（修复后）
watch(() => props.papers, (newPapers) => {
  tableData.value = newPapers.map(paper => ({
    ...paper,
    // 修复 1：indexing 处理（支持字符串/数组）
    indexing: Array.isArray(paper.indexing)
        ? paper.indexing.join(', ')
        : (typeof paper.indexing === 'string'
            ? paper.indexing.replace(/\[|\"|\]/g, '') // 清理 JSON 字符串引号
            : paper.indexing || ''),
    // 修复 2：publishDate 健壮性处理（空值 + 无效日期）
    publishDate: paper.publishDate
        ? (() => {
          const date = new Date(paper.publishDate);
          return isNaN(date.getTime()) ? '' : date.getFullYear();
        })()
        : '',
    // 修复 3：authorInfo 处理（支持非数组类型）
    authorInfo: paper.authorInfo
        ? (Array.isArray(paper.authorInfo)
            ? paper.authorInfo.map(author => author?.name || '').join(', ')
            : (typeof paper.authorInfo === 'string'
                ? paper.authorInfo
                : ''))
        : ''
  }))
}, { immediate: true })

// 切换字段选中状态
const toggleField = (field) => {
  field.selected = !field.selected
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
}

// 取消导出
const handleCancel = () => {
  dialogVisible.value = false
  ElMessage.info('已取消导出')
}

// 下载 Excel（修复后）
const handleExport = async () => {
  const selectedFields = fields.value.filter(f => f.selected);
  if (selectedFields.length === 0) {
    ElMessage.warning('请至少选择一个导出字段');
    return;
  }

  // 提取选中字段的 key
  const selectedFieldKeys = selectedFields.map(field => field.key);

  // 构建导出数据（过滤选中字段）
  const exportData = tableData.value.map(paper => {
    const filteredPaper = {};
    selectedFieldKeys.forEach(key => {
      // 兜底：空值转为空字符串，避免后端 null 问题
      filteredPaper[key] = paper[key] ?? '';
    });
    return filteredPaper;
  });

  try {
    // 调用导出接口（确保 exportPaper 配置了 responseType: 'blob'）
    const response = await exportPaper({
      fields: selectedFields,
      data: exportData
    });
    console.log("response",response)
    // 构建 Blob 并下载
    const blob=response
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = '论文导出.xlsx'; // 中文文件名需后端编码，或前端用 encodeURIComponent
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    window.URL.revokeObjectURL(url);
    ElMessage.success('导出成功');
  } catch (error) {
    // 错误处理
    if (error.response) {
      ElMessage.error(`导出失败：${error.response.data.msg || '服务器错误'}`);
    } else {
      ElMessage.error(`导出失败：${error.message}`);
    }
  }

  dialogVisible.value = false;
};
</script>

<style scoped>
.export-content {
  padding: 20px 0;
}
.field-selection {
  margin-bottom: 24px;
}
.section-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 12px;
  display: flex;
  align-items: center;
  gap: 4px;
}
.field-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}
.field-tag {
  cursor: pointer;
  user-select: none;
}
.field-tag:hover {
  border-color: #409eff;
}
.export-table {
  margin-top: 20px;
  border-radius: 4px;
}
:deep(.el-dialog__header) {
  margin-right: 0;
  border-bottom: 1px solid #dcdfe6;
}
:deep(.el-dialog__footer) {
  border-top: 1px solid #dcdfe6;
  padding: 20px;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
